{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Supervised Learning Algorithms: Ridge Regression"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*In this template, only **data input** and **input/target variables** need to be specified (see \"Data Input & Variables\" section for further instructions). None of the other sections needs to be adjusted. As a data input example, .csv file from IBM Box web repository is used.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Libraries"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Run to import the required libraries.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib notebook\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.model_selection import train_test_split"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Data Input and Variables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Define the data input as well as the input (X) and target (y) variables and run the code. Do not change the data & variable names **['df', 'X', 'y']** as they are used in further sections.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "### Data Input\n",
    "# df = \n",
    "\n",
    "### Defining Variables  \n",
    "# X = \n",
    "# y = \n",
    "\n",
    "### Data Input Example \n",
    "df = pd.read_csv('https://ibm.box.com/shared/static/q6iiqb1pd7wo8r3q28jvgsrprzezjqk3.csv')\n",
    "\n",
    "X = df[['horsepower']]\n",
    "y = df['price']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. The Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Run to build the model.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ridge regression linear model intercept: 12555.906666666666\n",
      "Ridge regression linear model coeff: [5036.92170125]\n",
      "\n",
      "R-squared score (training): 0.614\n",
      "R-squared score (test): 0.625\n",
      "\n",
      "Number of non-zero features: 1\n"
     ]
    }
   ],
   "source": [
    "from sklearn.linear_model import Ridge\n",
    "\n",
    "# train_test_split\n",
    "X_train, X_test, y_train, y_test = train_test_split(X, y,\n",
    "                                                   random_state = 0)\n",
    "# feature normalization\n",
    "scaler = StandardScaler()\n",
    "\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "# ridge regression def\n",
    "linridge = Ridge(alpha=20.0).fit(X_train_scaled, y_train)\n",
    "\n",
    "### intercept & coefficient, # of non-zero features & weights, R-squared for training & test data set\n",
    "print('Ridge regression linear model intercept: {}'\n",
    "     .format(linridge.intercept_))\n",
    "print('Ridge regression linear model coeff: {}\\n'\n",
    "     .format(linridge.coef_))\n",
    "print('R-squared score (training): {:.3f}'\n",
    "     .format(linridge.score(X_train_scaled, y_train)))\n",
    "print('R-squared score (test): {:.3f}\\n'\n",
    "     .format(linridge.score(X_test_scaled, y_test)))\n",
    "print('Number of non-zero features: {}'\n",
    "     .format(np.sum(linridge.coef_ != 0)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.1. Regularization parameter alpha on R-squared"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Run to check how alpha affects the model score.*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Ridge regression: effect of alpha regularization parameter\n",
      "\n",
      "Alpha = 0.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.62, r-squared test: 0.67\n",
      "\n",
      "Alpha = 1.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.62, r-squared test: 0.66\n",
      "\n",
      "Alpha = 10.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.62, r-squared test: 0.65\n",
      "\n",
      "Alpha = 20.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.61, r-squared test: 0.63\n",
      "\n",
      "Alpha = 50.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.58, r-squared test: 0.56\n",
      "\n",
      "Alpha = 100.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.52, r-squared test: 0.48\n",
      "\n",
      "Alpha = 1000.00\n",
      "num abs(coeff) > 1.0: 1, r-squared training: 0.15, r-squared test: 0.07\n",
      "\n"
     ]
    }
   ],
   "source": [
    "print('Ridge regression: effect of alpha regularization parameter\\n')\n",
    "for this_alpha in [0, 1, 10, 20, 50, 100, 1000]:\n",
    "    linridge = Ridge(alpha = this_alpha).fit(X_train_scaled, y_train)\n",
    "    r2_train = linridge.score(X_train_scaled, y_train)\n",
    "    r2_test = linridge.score(X_test_scaled, y_test)\n",
    "    num_coeff_bigger = np.sum(abs(linridge.coef_) > 1.0)\n",
    "    print('Alpha = {:.2f}\\nnum abs(coeff) > 1.0: {}, \\\n",
    "r-squared training: {:.2f}, r-squared test: {:.2f}\\n'\n",
    "         .format(this_alpha, num_coeff_bigger, r2_train, r2_test))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
